#! /usr/bin/env python
# -*- coding: utf8 -*-
#
#  gitlab irc sender
#  Copyright (C) 2016-2017  Andrei Karas (4144)
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import sys

try:
    from BaseHTTPServer import BaseHTTPRequestHandler
except ImportError:
    from http.server import BaseHTTPRequestHandler

from code.actionhandler import ActionHandler
from code.configuration import Configuration
from code.core import Core

class ServerHandler(BaseHTTPRequestHandler):
    def __init__(self, *args):
        self.project = None
        BaseHTTPRequestHandler.__init__(self, *args)

    def toStr(self, data):
        try:
            return data.decode()
        except AttributeError:
            return data

    def fromStr(self, data):
        try:
            return data.encode()
        except AttributeError:
            return data

    def returnError(self, code):
        self.send_response(code)
        self.end_headers()
        self.wfile.close()

    def returnData(self, code, response):
        self.send_response(code)
        self.send_header("Content-type", "text")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(self.fromStr(response))

    def version_string(self):
        return Configuration.http_web_server_name

    def do_HEAD(self):
        self.send_response(400)
        self.end_headers()
        self.wfile.close()

    def do_GET(self):
        self.send_response(400)
        self.end_headers()
        self.wfile.close()

    def do_POST(self):
        try:
            self.rfile._sock.settimeout(5)
        except AttributeError:
            pass # python3
        data = self.rfile.read(int(self.headers['Content-Length']))
        data = json.loads(self.toStr(data))

        self.actionHandler = ActionHandler()
        if Core.config.global_options.http_save_json == True or \
            Core.config.global_options.http_save_json == "all" or \
            Core.config.global_options.http_save_json == "any":
            self.actionHandler.saveJson(data)

        if self.actionHandler.validate(self.path, data) == False:
            if Core.config.global_options.http_return_error_if_not_supported == True:
                self.returnError(400)
            else:
                self.returnData(200, "OK")
            return

        self.returnData(200, "OK")
        self.actionHandler.processAction(self.path, data, self.headers)

    def log_message(self, format, *args):
        data = "{0}:{1} - - [{2}] {3}\n".format(self.client_address[0], self.client_address[1], self.log_date_time_string(), format % args)
        sys.stderr.write(data)
        Core.log.info(data)
